//
//  CTPCityModel.m
//  citipad
//
//  Created by Chih Yuan Liu on 3/15/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "CTPCityModel.h"
#import "constants.h"
#import "FMDatabase.h"
#import "FMDatabaseAdditions.h"


@implementation CTPCityModel

-(id)init{
	if(self = [super init]){
		mydb = [FMDatabase databaseWithPath:[constants GetDBPath]];
		[self createDB];
		[self loadIntoArray];
		//array = [[NSArray alloc] initWithObjects:@"Shanghai", @"Taipei", @"Beijing", @"New York", nil];
	}
	return self;
}

-(void) loadIntoArray{
	if([mydb open]){
		array = [[NSMutableArray alloc]init];
		FMResultSet *rs = [mydb executeQuery:@"select * from cities "];
		while ([rs next]) {
			[array addObject:[rs stringForColumn:@"name"]];
		}	
	}
}

-(void) createDB{
	if (![mydb open]) {
		NSLog(@"%s, Could not open db.", __PRETTY_FUNCTION__);
	}else {
		NSLog(@"%s, opened db", __PRETTY_FUNCTION__);
		[mydb executeUpdate:@"create table cities (name text)", nil];
	}
}

-(void) removeCity:(CTPCity*)city{
	mydb = [FMDatabase databaseWithPath:[constants GetDBPath]];
	NSUInteger index = [array indexOfObject:city.name];
	if(index != NSNotFound){
		[array removeObjectAtIndex:index];
		if([mydb open]){
			[mydb beginTransaction];
			NSLog(@"%s, %@", __PRETTY_FUNCTION__, city.name);
			[mydb executeUpdate:@"delete from cities where name =  ?" , city.name];
			[mydb commit];
			[mydb close];
		}
	}
}

-(void) addCity:(CTPCity*)city{
	mydb = [FMDatabase databaseWithPath:[constants GetDBPath]];
	NSLog(@"%s, %@", __PRETTY_FUNCTION__, city.name);
	NSUInteger index = [array indexOfObject:city.name];
	if(index == NSNotFound){
		if([mydb open]){
			[mydb beginTransaction];
			[mydb executeUpdate:@"insert into cities (name) values (?)" , city.name];
			[mydb commit];
			[mydb close];
			[array addObject:city.name];
		}
	}
}

-(NSInteger)GetCount{
	if(array==nil)
		return 0;
	return array.count;
}


-(CTPCity*) GetItemAtIndex:(int)index{
	CTPCity* city = [[CTPCity alloc] init];
	city.name = [NSString stringWithFormat:@"%@", [array objectAtIndex:index]];
	city.imageKey = [NSString stringWithFormat:@"%@.png", [array objectAtIndex:index]];
	return city;
}

@end
